package com.longshine.downcomp;

import com.longshine.log.Log;
import com.longshine.platform.equip.tcp.ProtocolDispacher;
import com.longshine.platform.equip.tcp.ProtocolUtil;
import com.longshine.tools.util.CommonUtil;

class HeartSendThread extends Thread{
	
	private EquipConnection conn;
	protected int systemType;
	protected int downNo;
	protected boolean isStart = true; 
	
	public HeartSendThread(EquipConnection conn,int systemType,int downNo){
		this.conn = conn;
		this.systemType = systemType;
		this.downNo = downNo;
	}
	
	public void run(){
		while(isStart){
			try {
				conn.sendStr(ProtocolUtil.createProtocol(downNo, 0, systemType, ProtocolDispacher.FUNCTION_HEARTBRET, null));
			} catch (Exception e) {
			}
			CommonUtil.delay(2000);
		}
	}
	
	public void stopSend(){
		isStart = false;
	}
}

public abstract class EquipSystem extends Thread {

	protected EquipConnection conn;
	protected int systemType;
	protected int downNo;
	protected int status;
	protected boolean isLogined = false;
	protected HeartSendThread heartThead; 
	public EquipSystem(int systemType,int downNo){
		this.systemType = systemType;
		this.downNo = downNo;
	}
	
	public void recv(String comm) throws Exception{
		int id = ProtocolUtil.getTaskId(comm);
		int funcCode = ProtocolUtil.getFunctionData(comm);
		String dataArea = ProtocolUtil.getDataAreaString(comm);
		recvCommand(id,funcCode,dataArea);
	}
	
	
	public abstract void recvCommand(int taskId,int functionCode,String dataArea) throws Exception;
	
	
	public void startWork() throws Exception{
		conn = new EquipConnection(UMInfoManager.getInfo().getIp(),UMInfoManager.getInfo().getPort());
		conn.startService();
		start();
	}
	
	public void work() {
		while(true){
			if(conn.isConnected()){
				if(!isLogined){
					try {
						if(login()){
							//发送心跳报文
							heartThead = new HeartSendThread(conn,systemType,downNo);
							heartThead.start(); 
							System.out.println("登陆成功");
							isLogined = true;
						}
						else{
							System.out.println("登陆失败");
						}
					} catch (Exception e) {
						
					}
				}
				else{
					try{
						String str = conn.recvStr();
						recv(str);
					}catch(Exception e){
						conn.stopConn();
						heartThead.stopSend();
						isLogined = false;
					}
				}
			}
			CommonUtil.delay(200);
		}
	}
	
	public void run(){
		work();
	}
	public boolean login() throws Exception{
		Log.println("尝试登陆");
		conn.sendStr(ProtocolUtil.createProtocol(downNo, 0, systemType, ProtocolDispacher.FUNCTION_LOGIN, null));
		String str = conn.recvStr();
		str = ProtocolUtil.getDataAreaString(str);
		if(ProtocolDispacher.DATAAREA_COMFIRM.equals(str)){
			return true;
		}
		return false;
	}
	
}
